package com.fqyd.campustransaction.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.fqyd.campustransaction.model.Cart;
import com.fqyd.campustransaction.model.Goods;
import com.fqyd.campustransaction.model.User;
import com.fqyd.campustransaction.utils.Tools;

/**
 * 购物车
 */
@Controller
@Scope(value = "prototype")
public class CartController extends BaseController {

	@RequestMapping("cart")
	public String cart(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("loguser");
		user = userService.getById(user.getId());
		List<Cart> carts = cartService.getByUserId(user.getId());
		List<Goods> goodsList = new ArrayList<>();
		double totalPrice = 0.0;
		for (int i = 0; i < carts.size(); i++) {
			Goods goods = goodsService.getById(carts.get(i).getGoodsId());
			if (goods == null) {
				continue;
			}
			goodsList.add(goods);
			totalPrice += goods.getPrice().doubleValue();
		}
		request.setAttribute("goodsList", goodsList);
		request.setAttribute("totalCount", goodsList.size());
		request.setAttribute("totalPrice", totalPrice);
		request.setAttribute("user", user);
		return "cart";
	}

	@RequestMapping("cart_add")
	public String cartAdd(HttpServletRequest request) {
		String goodsId = request.getParameter("goods_id");
		if (Tools.isEmpty(goodsId)) {
			return "redirect:index.do";
		}
		Goods goods = goodsService.getById(goodsId);
		if (goods == null) {
			return "redirect:index.do";
		}
		User user = (User) request.getSession().getAttribute("loguser");
		user = userService.getById(user.getId());
		if (cartService.checkGoodsId(user.getId(), goodsId)) {
			Cart cart = new Cart();
			cart.setId(Tools.createID());
			cart.setUserId(user.getId());
			cart.setGoodsId(goods.getId());
			cartService.add(cart);
		}
		return "redirect:cart.do";
	}

	@RequestMapping("cart_delete")
	public String cartDelete(HttpServletRequest request) {
		String goodsId = request.getParameter("goods_id");
		if (Tools.isEmpty(goodsId)) {
			return "redirect:index.do";
		}
		User user = (User) request.getSession().getAttribute("loguser");
		user = userService.getById(user.getId());
		cartService.deleteCart(user.getId(), goodsId);
		return "redirect:cart.do";
	}
}
